const { baseUrl } = require('./baseUrl.js');
class Task {
  constructor (param) {
    this.practiceId = param.practiceId
    this.sceneType = param.sceneType
    this.connectTimes = param.connectTimes
    this.connect()
  }
  connect () {
    const { practiceId, sceneType, connectTimes } = this
    const options = {
      url: `wss://${baseUrl}/nls/nls/websocket/${practiceId}/${wx.getStorageSync("token")}/${connectTimes}/${sceneType}`,
      success: (resConnect) => {
        console.log('连接成功')
      },
      fail: (resConnectError) => {
        console.log('连接失败')
      },
    }
    console.log(options.url)
    const socketTask = wx.connectSocket(options)
    this.socketTask = socketTask
  }
  reConnect (connectTimes) {
    const socketTask = this.socketTask
    if (socketTask && socketTask.readyState !== 1) {
      console.log('重连')
      if (connectTimes > 20) {
        wx.showToast({
          title: '网络开小差了，请返回重新进入',
          icon: 'none',
          duration: 1000,
        })
      } else {
        wx.showToast({
          title: '正在重新连接',
          icon: 'none',
          duration: 500,
          complete: () => {
            this.connectTimes++
            this.connect()
          }
        })
      }
    }
  }
}

// 检测麦克风权限
const checkRecord = () => {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.record']) {
          wx.authorize({
            scope: 'scope.record',
            success: () => {
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              resolve()
            },
            fail: () => {
              wx.showModal({
                content: '检测到您没有打开麦克风权限，是否去设置打开?',
                cancelColor: '#666666',
                cancelText: '取消',
                confirmText: '确认',
                confirmColor: '#006DE7',
                success (res) {
                  if (res.confirm) {
                    wx.openSetting({
                      success: res => {
  
                      }
                    })
                  } else if (res.cancel) {
                    
                  }
                }
              })
              startSocket()
            }
          })
        } else {
          resolve()
        }
      }
    })
  })
}

// 处理陪练数据
const initTrainData = (e, talkList) => {
  const data = JSON.parse(e.data)
  console.log(data, '收到消息', new Date())
  // console.log(data)
  if (data.userMessage) {
    // 用户说话
    talkList.length - 3 >= 0 && (talkList[talkList.length - 3].retryDisabled = true) // 说话后上一句就不能重练了
    talkList[talkList.length - 1].word = data.userMessage
  }
  if (data.nodeDeductInfos && data.nodeDeductInfos.length > 0) {
    // 评分详情
    data.nodeDeductInfos.map((j, o) => {
      j.ruleName = scorePoint[j.ruleType]
    })
    talkList[talkList.length - 1].open = false
    talkList[talkList.length - 1].nodeDeductInfos = data.nodeDeductInfos
  }
  if (data.robotMessage
    && (talkList.length === 0 || talkList[talkList.length - 1].word)) {
    // 机器人说话&&不是重连
    talkList.push({
      role: 'robot',
      word: data.robotMessage,
    })
  }
  if (data.recAnswer
    && (talkList.length === 0 || talkList[talkList.length - 1].word)
    && !data.isEnd
    && !data.userMessage) {
    // 提示，重连表示'我'未说话，无需显示多条提示
    talkList.push({
      role: 'customer',
      tips: data.recAnswer,
    })
  }
  return talkList
}

const writeFile = (url) => {
  return new Promise((resolve, reject) => {
    const filePath = `${wx.env.USER_DATA_PATH}/temp_${new Date().getTime()}.wav`
    wx.getFileSystemManager()
    .writeFile({
      filePath,
      data: url,
      encoding: 'binary',
      success: res => {
        console.log(filePath)
        const { canPlay } = this.data
        console.log(this.data.isEnd)
        if (canPlay) {
          innerAudioContext.autoplay = true
          innerAudioContext.src = filePath
          innerAudioContext.play()
        }
      },
      fail: res => {
        console.log('fail')
        console.log(res)
      }
    })
  })
}

export {
  Task,
  checkRecord,
  initTrainData,
}